package com.apps.realtyportal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.apps.essentials.AddTapLocationOverlay;
import com.apps.essentials.AddTapLocationOverlay2;
import com.apps.essentials.AddUserLocationOverlay;
import com.apps.essentials.AlertDialogManager;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.MultipleSearching.Exchanger;
import com.apps.realtyportal.MultipleSearching.MapFragment;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.jason.apps.buyer.Buyer;
import com.jason.apps.buyer.Favorites;
import com.jason.apps.dashboard.DashBoard;
import com.jason.apps.fromdashboard.Agent;
import com.readystatesoftware.maps.OnSingleTapListener;

public class MultipleSearching2 extends SherlockFragmentActivity implements TextWatcher{
	
	private AutoCompleteTextView location_search;
	private AutoCompleteTextView price_search;
	private AutoCompleteTextView type_search;
	private String lists_of_addrs[] = new String[] { "Alcantara",
			"Alcoy",
			"Alegria",
			"Aloguinsan",
			"Argao",
			"Asturias",
			"Badian",
			"Balamban",
			"Bantayan",
			"Barili",
			"Bogo",
			"Boljoon",
			"Borbon",
			"Carcar",
			"Carmen",
			"Catmon",
			"Cebu City",
			"Compostela",
			"Consolacion",
			"Cordova",
			"Daanbantayan",
			"Dalaguete",
			"Danao City",
			"Dumanjug",
			"Ginatilan",
			"Lapu-Lapu City",
			"Liloan",
			"Madridejos",
			"Malabuyoc",
			"Mandaue City",
			"Medellin",
			"Minglanilla",
			"Moalboal",
			"Naga",
			"Oslob",
			"Pilar",
			"Pinamungahan",
			"Poro",
			"Ronda",
			"Samboan",
			"San Fernando",
			"San Francisco",
			"San Remigio",
			"Santa Fe",
			"Santander",
			"Sibonga",
			"Sogod",
			"Tabogon",
			"Tabuelan",
			"Talisay City",
			"Toledo City",
			"Tuburan",
			"Tudela" };
	private String lists_of_prices[] = new String[] { 
			"200000.00",
			"300000.00",
			"400000.00",
			"500000.00",
			"600000.00",
			"700000.00",
			"800000.00",
			"900000.00",
			"1000000.00",
			"2000000.00",
			"3000000.00",
			"4000000.00",
			"5000000.00",
			"6000000.00",
			"7000000.00",
			"8000000.00",
			"9000000.00",
			"10000000.00"};
	private String lists_of_types[] = new String[] { 
			"Codominium",
			"Building",
			"Subdivision",
			"House",
			"Office"};
	private ActionBar actionbar;
	private MapFragment mMapFragment;
	private Fragment mVisible = null;
	List<Overlay> newmapOverlays;
	CustomOverlayItem overlayItem3;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	AddTapLocationOverlay taplocation;
	MapController controlmap;
	int minLat = Integer.MAX_VALUE;
	int minLong = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int maxLong = Integer.MIN_VALUE;
	GeoPoint gp;
	Drawable drawable,dh,db,ds;
	int lat;
	int lon;
	private Button btnsearch;
	ArrayList colat,colon,coaddress,cotype=new ArrayList();
	AlertDialogManager alert = new AlertDialogManager();
	
	//from web service starts here
	ConsumeWebService c;
	public final static ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	
	Context appContext;
	HashMap<String, String> map;
	 SherlockFragmentActivity fa;
		
	public static final String KEY_ID = "property_id";
	public static final String KEY_NAME = "property_name";
	public static final String KEY_DESCRIPTION = "property_description";
	public static final String KEY_PRICE = "price";
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_TYPE = "type";
	public static final String KEY_IMAGE = "main_image";
	public static final String KEY_PERSONFNAME="firstname";
	public static final String KEY_PERSONLNAME="lastname";
	public static final String KEY_PERSONCONTACT="mobile";
	String datatr;


	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.multiplesearching2);
		actionbar = getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowTitleEnabled(true);
		location_search = (AutoCompleteTextView)findViewById(R.id.search_location);
		location_search.addTextChangedListener(this);
		price_search = (AutoCompleteTextView)findViewById(R.id.search_price);
		price_search.addTextChangedListener(this);
		type_search = (AutoCompleteTextView)findViewById(R.id.search_type);
		type_search.addTextChangedListener(this);
		
		//adapters
		location_search.setThreshold((Integer)0);
		price_search.setThreshold((Integer)0);
		type_search.setThreshold((Integer)0);
		location_search.setAdapter(new ArrayAdapter(this, R.layout.suggestions_list, lists_of_addrs));
//		location_search.setAdapter(new ArrayAdapter(this, R.layout.suggestions_list,R.array.list_of_locations));
		price_search.setAdapter(new ArrayAdapter(this, R.layout.suggestions_list, lists_of_prices));
		type_search.setAdapter(new ArrayAdapter(this, R.layout.suggestions_list, lists_of_types));
		c = new ConsumeWebService();
		location_search.setOnTouchListener(new OnTouchListener(){
			
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				
				return false;
			}
			
		});
		
		
		//fragments start here
		Exchanger.mMapView = new MapView(this,"07QrqGLNNbvFFh9LUuMashT4Bukx3tMIwwfrOaA");
		newmapOverlays = Exchanger.mMapView.getOverlays();
		
		Exchanger.mMapView.setBuiltInZoomControls(true);
		controlmap = Exchanger.mMapView.getController();		
		newmapOverlays = Exchanger.mMapView.getOverlays();		
		
		setupFragments();
		// We manually show the list Fragment.
		showFragment(mMapFragment);
		// start here
		actionbar.setDisplayShowCustomEnabled(true);
		View actionbar_search = LayoutInflater.from(this).inflate(
				R.layout.multiple_search_custom, null);
		btnsearch = (Button) actionbar_search.findViewById(R.id.search);
		
		btnsearch.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
//				priceSearching();
//				String locationselected = txtlocation_searching.getText().toStrinCg();
//				Toast.makeText(getBaseContext(), "no locations"+locationselected, Toast.LENGTH_LONG).show();
//				searchCriteria2();
				mylist.clear();
				new searchCriteria().execute();
			}
		});
		actionbar.setCustomView(actionbar_search);		
	}

	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
		
	}

	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}
	private void setupFragments() {
		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();

		/*
		 * If the activity is killed while in BG, it's possible that the
		 * fragment still remains in the FragmentManager, so, we don't need to
		 * add it again.
		 */
		mMapFragment = (MapFragment) getSupportFragmentManager()
				.findFragmentByTag(MapFragment.TAG);
		if (mMapFragment == null) {
			mMapFragment = new MapFragment();
			ft.add(R.id.searchfragment_container, mMapFragment, MapFragment.TAG);
		}
		ft.hide(mMapFragment);

		ft.commit();
	}
	
//	public void getProperty(String address, double price, double limit, String type ){
//		c = new ConsumeWebService();
//		 String data = c.MultiCriteriaSearch(address, price, limit, type);
//		 datatr = data;
//		 try {
//
//				JSONArray array = new JSONArray(data);
//				
//				for (int i = 0; i < array.length(); i++) {
//					map = new HashMap<String, String>();
//					
//					JSONObject e = array.getJSONObject(i);
//					map.put("property_id", e.getString(KEY_ID));
//					map.put("property_name", e.getString(KEY_NAME));
//					map.put("property_description", e.getString(KEY_DESCRIPTION));
//					map.put("price", e.getString(KEY_PRICE));
//					map.put("latitude", e.getString(KEY_LATITUDE));
//					map.put("longitude", e.getString(KEY_LONGITUDE));
//					map.put("address", e.getString(KEY_ADDRESS));
//					map.put("type", e.getString(KEY_TYPE));
//					map.put("image", e.getString(KEY_IMAGE));
//					map.put("firstname", e.getString("firstname"));
//					map.put("lastname", e.getString("lastname"));
//					map.put("mobile", e.getString("mobile"));
//					map.put("email", e.getString("email_address"));
//										
//					mylist.add(map);
//
//				}
//			} catch (JSONException e) {
//				Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
//			}finally{
//				
//			}
////		 Toast.makeText(getApplicationContext(), ""+data, Toast.LENGTH_LONG).show();
//	}

	/**
	 * This method shows the given Fragment and if there was another visible
	 * fragment, it gets hidden. We can just do this because we know that both
	 * the mMyListFragment and the mMapFragment were added in the Activity's
	 * onCreate, so we just create the fragments once at first and not every
	 * time. This will avoid facing some problems with the MapView.
	 * 
	 * @param fragmentIn
	 *            The fragment to show.
	 */
	private void showFragment(Fragment fragmentIn) {
		if (fragmentIn == null)
			return;

		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);

		if (mVisible != null)
			ft.hide(mVisible);

		ft.show(fragmentIn).commit();
		mVisible = fragmentIn;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * This class acts as an exchanger between the Activity and the MapFragment,
	 * so if you want, you can put the MapFragment class in a separate java
	 * file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class Exchanger {
		// We will use this MapView always.
		public static MapView mMapView;
	}

	public static class MapFragment extends SherlockFragment {

		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// The Activity created the MapView for us, so we can do some init
			// stuff.

			final ViewGroup parent = (ViewGroup) Exchanger.mMapView.getParent();
			if (parent != null)
				parent.removeView(Exchanger.mMapView);

			Exchanger.mMapView.setClickable(true);
			Exchanger.mMapView.setBuiltInZoomControls(true); // If you want.

			/*
			 * If you're getting Exceptions saying that the MapView already has
			 * a parent, uncomment the next lines of code, but I think that it
			 * won't be necessary. In other cases it was, but in this case I
			 * don't this should happen.
			 */

			return Exchanger.mMapView;
		}
	}
	public void searchCriteria2(){
	    String address;
	    String price;	   
	    String type;
	    String range="100000";
	    String cprice;
    	address = location_search.getText().toString().trim();
    	price = price_search.getText().toString().trim();
    	type = type_search.getText().toString().trim();
    	
    	if(!address.matches("") && !price.matches("") && type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute address and price", Toast.LENGTH_LONG).show();
    	}else if(!address.matches("") && price.matches("") && type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute address", Toast.LENGTH_LONG).show();
    	}else if(!address.matches("") && price.matches("") && !type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute address and type", Toast.LENGTH_LONG).show();
    	}else if(address.matches("") && !price.matches("") && type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute price", Toast.LENGTH_LONG).show();
    	}else if(address.matches("") && price.matches("") && !type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute type", Toast.LENGTH_LONG).show();
    	}else if(address.matches("") && !price.matches("") && !type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute price and type", Toast.LENGTH_LONG).show();
    	}else if(!address.matches("") && !price.matches("") && !type.matches("")){
    		Toast.makeText(getApplicationContext(), "execute all", Toast.LENGTH_LONG).show();
    	}else{
    		Toast.makeText(getApplicationContext(), "no data found", Toast.LENGTH_LONG).show();
    	}
	}
	public class searchCriteria extends AsyncTask<Void, Void, Void> {
	 	SherlockFragmentActivity activity;
	    public ProgressDialog dialog=new ProgressDialog(MultipleSearching2.this);	    
	    boolean results=false;
	    String address;
	    String price;	   
	    String type;
	    String range="100000";
	    String cprice;
	    double prices=0;
	   
	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading data...");
	            this.dialog.show();
	            
	    }

	    protected Void doInBackground(final Void... unused) {
	    	address = location_search.getText().toString().trim().toLowerCase();
	    	price = price_search.getText().toString().trim().toLowerCase();
	    	type = type_search.getText().toString().trim().toLowerCase();
	    	String data = null;
	    	
    	    		
	    		//String data = c.executeCategorySearch(address, price, type);
				 try {
				    	if(!address.matches("") && !price.matches("") && type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute address and price", Toast.LENGTH_LONG).show();
				    		data = c.AddressPriceSearch(address, price);
				    	}else if(!address.matches("") && price.matches("") && type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute address", Toast.LENGTH_LONG).show();
				    		data = c.ALLAddressSearch(address);
				    	}else if(!address.matches("") && price.matches("") && !type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute address and type", Toast.LENGTH_LONG).show();
				    		data = c.AddressTypeSearch(address, type);
				    	}else if(address.matches("") && !price.matches("") && type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute price", Toast.LENGTH_LONG).show();
				    		data = c.ALLPriceSearch(price);
				    	}else if(address.matches("") && price.matches("") && !type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute type", Toast.LENGTH_LONG).show();
				    		data = c.AllTypeSearch(type);
				    	}else if(address.matches("") && !price.matches("") && !type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute price and type", Toast.LENGTH_LONG).show();
				    		data = c.PriceTypeSearch(price, type);
				    	}else if(!address.matches("") && !price.matches("") && !type.matches("")){
				    		//Toast.makeText(getApplicationContext(), "execute all", Toast.LENGTH_LONG).show();
				    		data = c.executeCategorySearch(address, price, type);
				    	}else{
				    		Toast.makeText(getApplicationContext(), "no data found", Toast.LENGTH_LONG).show();				    		
				    	}	
						JSONArray array = new JSONArray(data);
						
						for (int i = 0; i < array.length(); i++) {
							map = new HashMap<String, String>();
							
							JSONObject e = array.getJSONObject(i);
							map.put("property_id", e.getString(KEY_ID));
							map.put("property_name", e.getString(KEY_NAME));
							map.put("property_description", e.getString(KEY_DESCRIPTION));
							map.put("price", e.getString(KEY_PRICE));
							map.put("latitude", e.getString(KEY_LATITUDE));
							map.put("longitude", e.getString(KEY_LONGITUDE));
							map.put("address", e.getString(KEY_ADDRESS));
							map.put("type", e.getString(KEY_TYPE));
							map.put("image", e.getString(KEY_IMAGE));
							map.put("firstname", e.getString("firstname"));
							map.put("lastname", e.getString("lastname"));
							map.put("mobile", e.getString("mobile"));
							map.put("email", e.getString("email_address"));
												
							mylist.add(map);
						}
				
			}catch(Exception e){
				//Log.e("error", e.getMessage());
			}
	    	
	        return null; 
	    }
	    
	    protected void onPostExecute(Void result) {
			
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();	            
	        }	    	 
//	    	Toast.makeText(getApplicationContext(), ""+mylist, Toast.LENGTH_LONG).show();
	    	if(!mylist.isEmpty()){
			runOnUiThread(new Runnable(){
				public void run() {	
			    	for(int i = 0; i<mylist.size(); i++){
			    		HashMap<String, String> map = mylist.get(i); 		
			    		String tr1 = (String) map.get(KEY_LATITUDE);
			    		String tr2 = (String) map.get(KEY_LONGITUDE);
						String pname = map.get(KEY_NAME);
						String pdescription = map.get(KEY_DESCRIPTION);
						String paddress = map.get(KEY_ADDRESS);
						String pimage = map.get(KEY_IMAGE);
						String ptype = map.get(KEY_TYPE);
						String pprice = map.get(KEY_PRICE);
						String pindex = map.get(KEY_ID).toString();
						String pagent = map.get("firstname");
						String pcontact = map.get("mobile");
			    		if(!tr1.matches("") && !tr2.matches("")){
			    			int lat1 = Integer.valueOf((String) tr1);
			    			int  long2= Integer.valueOf((String) tr2);
//			    			double cinttr1 = (double) lat1/1E6;
//			    			double cinttr2 = (double) long2/1E6;

							gp = new GeoPoint(lat1, long2);
							minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
						    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
						    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
						    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );
							if(ptype.equalsIgnoreCase("building")){
								drawable = getResources().getDrawable(R.drawable.building2);
							}else if(ptype.equalsIgnoreCase("house")){
								drawable = getResources().getDrawable(R.drawable.house2);
							}else if(ptype.equalsIgnoreCase("subdivision")){
								drawable = getResources().getDrawable(R.drawable.subdivision2);
							}else if(ptype.equalsIgnoreCase("condominium")){
								drawable = getResources().getDrawable(R.drawable.building2);
							}
						    
//					    	drawable = getResources().getDrawable(R.drawable.building2);
					    	newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
							  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
										"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,pcontact,
										pimage);
										newitemizedOverlay2.addOverlay(overlayItem3);
										newmapOverlays.add(newitemizedOverlay2);
										newitemizedOverlay2.populateNow();	
//			    			Toast.makeText(getApplicationContext(), "Converted int lat "+lat1+"Converted int lon "+long2, Toast.LENGTH_LONG).show();
//			    			Toast.makeText(getApplicationContext(), "Converted double lat "+cinttr1+"Converted double lon "+cinttr2, Toast.LENGTH_LONG).show();
			    			
			    		}
//			    		Toast.makeText(getApplicationContext(), "data lat "+tr1+" data lon "+tr2, Toast.LENGTH_LONG).show();
			    	}
				}			
			});
	    	}else if(mylist.isEmpty()){
	    		alert.showAlertDialog(MultipleSearching2.this, "NO DATA FOUND",
						"Sorry no data found. Try to check connection",
						false);
	    		
	    		newmapOverlays.clear();
	    		controlmap.animateTo(new GeoPoint(10309416,123893509));
	    		controlmap.setZoom(14);
	    	}
			controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
			controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
			Exchanger.mMapView.invalidate();				
			
	    	
	    	}	    
  	}		
	}
	

	

